 <template>
  <article class="page">
    <homeHeaderbar></homeHeaderbar>

    <section class="frame-content-sub bg-default">

      <redCloudHeadMenu></redCloudHeadMenu>

      <ul class="btn-menu pdh-10">
        <li @click="clickMenu('2')" :class="{'active': currentIndex=='2'}"><span>课件点播</span></li>
        <li @click="clickMenu('4')" :class="{'active': currentIndex=='4'}"><span>每日新闻</span></li>
        <li @click="clickMenu('3')" :class="{'active': currentIndex=='3'}"><span>红云FM</span></li>
      </ul>


      <section class="d-scroll-2head list-news-img bg-white">
        <cube-slide
          ref="slide"
          :loop="loop"
          :initial-index="0"
          :auto-play="autoPlay"
          :show-dots="showDots"
          :options="slideOptions"
          @change="changePage"
        >

        <cube-slide-item v-for="(item,index) in componentIds" :key="index">
          <longVideoListComponent :currentIndex="item"></longVideoListComponent>
        </cube-slide-item>
        </cube-slide>
      </section>
    </section>
    <footerbar></footerbar>
  </article>
</template>


<script>
  import redCloudHeadMenu from '@/components/common/redCloudHeadMenu.vue'
  import likeUpsComponent from '@/components/common/likeUpsComponent.vue'
  import homeHeaderbar from '@/components/layout/homeHeaderbar.vue'
  import footerbar from '../../../components/layout/footerbar.vue'
  import longVideoListComponent from './longVideoListComponent.vue'
  export default {
    components: {redCloudHeadMenu, homeHeaderbar, likeUpsComponent, footerbar, longVideoListComponent},
    name: 'longVideo',
    data () {
      return {
        isLoading:true,
        componentIds: [2, 4, 3],
        playing: false,
        list: [],
        guiyanNews: [],
        files: [],
        attachmentList: [],
        channelId: '19a64c36d6ff4442948bb99bb1a06e77',
        currentIndex: '',
        scrollHeight: '300',
        quickScrollHeight: '30',
        scrollDuration: '300',
        clickDuration: '10',
        clickDistance: '30',
        pageIndex: 1,
        pageSize: 10,
        detail: {},
        navIds: {
          1: '19a64c36d6ff4442948bb99bb1a06e77',
          2: 'd848e28cd5a14617be976be23efed142',
          3: '7f14dd4a9b7246abbf9d1a750a2a42e3',
          4: '37389fc4c7e945e48ddd80f996cac063',
        },
        options: {
          pullUpLoad: true,
          scrollbar: false
        },
        userInfo: {},
        loop: false,
        autoPlay: false,
        showDots: false,
        slideOptions: {
          listenScroll: true,
          probeType: 3,
          directionLockThreshold: 0
        },
        scrollOptions: {
          directionLockThreshold: 0
        }
      }
    },
    created () {
      this.userInfo = this.$localStorage.get('userInfo')
//      this.fetchClass()
//      this.fetchList
      let index = this.$route.query.index || '2'
      this.$nextTick(() => {
        this.clickMenu(index)
      })
      this.init()
    },
    activated(){
      this.init()
    },
    beforeRouteLeave(to, from, next){
      // 详情页时缓存组件
      this.$route.meta.keepAlive = ['longVideoList','videoDetail'].indexOf(to.name) !== -1
      if(this.$route.meta.keepAlive) {
        this.$store.commit('addRoute','longVideo')
      }else {
        this.$store.commit('removeRoute','longVideo')
      }
      next();
    },
    watch: {
      currentIndex (newVal) {
        this.switchTab(newVal)
      }
    },
    methods: {
      init(){
        this.$store.commit('removeRoute','longVideoList')
      },
      play (e) {
        e.target.play()
      },
      onplay (e) {
        setTimeout(() => {
          this.playing = true
        }, 1000)
      },
      goUserInfo () {
        if (this.detail.createUser) {
          this.$router.push({name: 'microVideo', query: {userId: this.detail.createUser}})
        }
      },
      getUserName (item) {
        return item.detail.newsContent.nickname || item.detail.newsContent.createUserName || item.createUserName || '未知'
      },
      getVideoTitle (item) {
        console.log(item)
        return item.detail && item.detail.newsContent.title
      },
      goDetail (item) {
        let currentIndex = parseInt(this.currentIndex)
        if ((currentIndex === 2 || currentIndex === 3) && item.zhuanji === 1) {
          this.$store.state.longVideoList = item
          this.$router.push({name: 'longVideoList', query: {id: item.id}})
        } else {
          this.$store.state.videoDetail = item
          this.$store.state.newsDetail = item
          this.$router.push({name: 'videoDetail', query: {id: item.id}})
        }
      },
      comment (item) {
        console.log('comment', item)
        this.$store.state.newsDetail = item
//        this.$router.push({name: 'commentList', query: {id: item.id}})
        this.$createCommentComponent({
          $props: {
            _contentId: item.id
          }
        }).show()
      },
      getPoster (item) {
        return this.tools.getImgUrl(item.listPic)
      },
      playVideo (index) {
        let videos = document.querySelectorAll('video')
        if (videos.length < 1) {
          return false
        }
        for (let i = 0; i < videos.length; i++) {
          videos[i].pause()
        }
        if (index >= videos.length) {
          this.$store.state.newsDetail = this.detail = this.list[index - 1]
          videos[index - 1].play()
          return false
        }
        this.$store.state.newsDetail = this.detail = this.list[index]
        videos[index].play()
        console.log(this.detail)
      },
      change (currIndex, total) {
        this.playVideo(currIndex)
        if (total - currIndex < 3) {
          this.fetchList()
        }
      },
      changePage (currIndex) {
        this.currentIndex = this.componentIds[currIndex]
      },
      /*每日新闻*/
      openUrl (url) {
        url = url || 'https://epaper.gywb.cn/ipaper/gyrb/html/2019-04/05/node_8935.htm'
        // 2020年7月1日11:20:07 更换
        console.log('打开外部链接：', url)
        if (window.android && window.android.openUrl) {
          window.android.openUrl(url)
        }
        return
      },
      /*跳转到对应tab*/
      switchTab (index) {
        if (this.$route.query.index != index) {
          this.$router.replace({path: this.$route.name, query: {index: index}})
        }
        setTimeout(() => {
          let indexV = this.componentIds.indexOf(index)
          this.$refs.slide.slide && this.$refs.slide.slide.goToPage(indexV, 0, 300)
        }, 0)
      },
      clickMenu (index) {
        if (this.$route.query.index != index) {
          this.$router.replace({path: this.$route.name, query: {index: index}})
        }
        index = parseInt(index)
        this.currentIndex = index
        this.$store.state.isVideo = true
        if (index === 3) {
          this.$store.state.isVideo = false
        }
        this.switchTab(index)
      },
      fetchList (id) {
        this.isLoading = true
        id = id || this.channelId
        let data = {
          "channelId": id || "",
          "pageNo": this.pageIndex,
          "pageSize": this.pageSize
        }
        return this.fetchService.contentPage(data).then(res => {
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '接口出错，请联系管理员')
          }
          if (this.pageIndex === 1) {
            this.detail = res.data.page[0]
          }
          this.isLoading = false
          if (this.currentIndex == 1) {
            this.fetchDetail(res.data.page)
          } else {
            if (this.pageIndex === 1) {
              this.list = []
            }
            this.list = this.list.concat(res.data.page)
          }
          this.pageIndex++
          // if (res.data.page.length === 0) {
          //   this.tools.tip('暂无更多')
          // }
          return res
        })
      },
      bigVideoPage () {
        this.isLoading = true
        let data = {
          'pageNo': this.pageIndex,
          'pageSize': this.pageSize
        }
        return this.fetchService.bigVideoPage(data).then(res => {
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '接口出错，请联系管理员')
          }
          this.isLoading = false
          if (this.pageIndex === 1) {
            this.list = []
          }
          if (res.data.album && res.data.album.length > 0) {
            res.data.album.map((v) => {
              v.title = v.channelName
              v.listPic = v.pic
              v.zhuanji = 1
            })
            this.list = this.list.concat(res.data.album)
          }
          if (res.data.page && res.data.page.length > 0) {
            this.list = this.list.concat(res.data.page)
          }
          this.pageIndex++
          // if (!res.data.album && !res.data.page) {
          //   this.tools.tip('暂无更多')
          // } else if (!res.data.album && (res.data.page && res.data.page.length === 0)) {
          //   this.tools.tip('暂无更多')
          // } else if (!res.data.page && (res.data.album && res.data.album.length === 0)) {
          //   this.tools.tip('暂无更多')
          // } else if (res.data.album.length === 0 && res.data.page.length === 0) {
          //   this.tools.tip('暂无更多')
          // }
          return res
        })
      },
      fmPage () {
        this.isLoading = true
        let data = {
          'pageNo': this.pageIndex,
          'pageSize': this.pageSize
        }
        return this.fetchService.fmPage(data).then(res => {
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '接口出错，请联系管理员')
          }
          this.isLoading = false
          if (this.pageIndex === 1) {
            this.list = []
          }
          if (res.data.album && res.data.album.length > 0) {
            res.data.album.map((v) => {
              v.title = v.channelName
              v.listPic = v.pic
              v.zhuanji = 1
            })
            this.list = this.list.concat(res.data.album)
          }
          if (res.data.page && res.data.page.length > 0) {
            this.list = this.list.concat(res.data.page)
          }
          this.pageIndex++
          return res
        })
      },
      fetchDetail (list) {
        let me = this
        list.forEach((v, index) => {
          (function(v, index){
            me.fetchService.contentPageDetail(v.id).then(res => {
              if (me.currentIndex != 1) {
                return false
              }
              v.detail = res.data
              me.list.push(v)
              setTimeout(() => {
                if (index === 0 && me.pageIndex <= 2) {
                  me.playVideo(0)
                }
              }, 2000)

            })
          })(v, index)
        })
      },
      getVideoSrc (item) {
        return this.tools.getImgUrl(item.detail.files[0].fileId)
      },
      fetchClass () {
        let data = {
          "beyond": "",
          "channelName": "",
          "channelType": "1",
          "createTime": "",
          "createUser": "",
          "delFlag": "",
          "description": "",
          "parentId": "fce9737eec9e4442b89ddab146c5706c",
          "id": "",
          "isCommont": "",
          "pic": "",
          "publicWay": "0",
          "tenantId": "",
          "treePath": "",
          "updateTime": "",
          "updateUser": ""
        }
        this.fetchService.childChannels(data).then(res => {
          console.log(res)
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '接口出错，请联系管理员')
          }
          if (res.data.length < 1) {
            return this.tools.tip('没有栏目')
          }
          this.menuList = res.data[0].childrens
          this.clickMenu(this.menuList[0], 0)
        })
      },
      hasList () {
        return this.list.length > 0
      },
      postVideo () {
        this.$store.state.newsDetail = this.detail
        this.$router.push({name: 'postVideo'})
      },
      uploadFile (file) {
        let uploadFile = file[0]
        let formData = new FormData()
        formData.append('file', uploadFile)
        this.fetchService.o_upload(formData).then((res) => {
          if (res.code !== 0) {
            return this.tools.tip(res.message)
          }
          let ret = res.data
          this.attachmentList.push({'fileId': res.data.fileId, 'fileName': uploadFile.name, 'totalBytes': res.data.totalBytes, 'path': ret.path})
          this.saveVideoInfo([ret])
        })
      },
      saveVideoInfo (files) {
        let params = {
          "channelId": this.channelId,
          "comments": 0,
          "downs": 0,
          "ups": 0,
          source: '筑红云APP',
          checkStatus: 0,
          "status": 2,
          "views": 0,
          "sortNum": 0,
          "contents": "分享视频" + Date.now(),
          "isTop": 0,
          "files": files,
          "title": "分享视频" + Date.now()
        }
        this.fetchService.addOrUpdate(params).then(res => {
          if (res.code !== 0) {
            return this.tools.tip(res.message || '操作失败')
          }
          this.tools.tip('上传成功')
        })
      },
      like () {
        let params = {
          contentId: this.detail.id,
          type: 2
        }
        this.fetchService.updateCount(params).then(res => {
          this.detail.ups ++
        })
      },
      onPullingUp () {
        if (this.currentIndex === '2') {
          this.bigVideoPage().then(res => {
            setTimeout(() => {
              this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate(true, false)
              this.options.isPullUpLoad = false
            }, 100)
          })
        } else if (this.currentIndex === '3') {
          this.fmPage().then(res => {
            setTimeout(() => {
              this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate(true, false)
              this.options.isPullUpLoad = false
            }, 100)
          })
        } else {
          this.fetchList().then(res => {
            setTimeout(() => {
              this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate(true, false)
              this.options.isPullUpLoad = false
            }, 100)
          })
        }
      },
      getRole () {
        if (this.userInfo.type === '10') {
          return false
        } else {
          return true
        }
      },
      fetchUrl (id) {
        let data = {
          "channelId": id || "",
          "pageNo": '1',
          "pageSize": '1'
        }
        this.tools.showLoading()
        return this.fetchService.contentPage(data).then(res => {
          this.tools.hideLoading()
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '接口出错，请联系管理员')
          }
          return res.data.page[0].sourceUrl
        })
      },
      /*获取新闻列表*/
      getNewsList (id) {
        let data = {
          'channelId': id || '',
          'pageNo': 1,
          'pageSize': 1
        }
        return this.fetchService.contentPage(data).then(res => {
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '接口出错，请联系管理员')
          }
          return res.data.page[0]
        })
      },
      /*每日新闻*/
      fetchGuiyanNews () {
        let channelIds = [
          '83def6bfa8654230ad9dd10e398985e3', // 央视新闻联播
          '7e841ccc77484535be00a3d3e205901f', // 贵州新闻联播
          'db96d49c341644d78a9c2743b6042ff4', // 贵阳新闻联播
          '3a9d846b09aa4ef6b854593e4135076e', // 贵阳日报
        ]
        let me = this
        let list = []
        let temp = []
        new Promise((resolve, reject) => {
          channelIds.forEach((v, index) => {
            (function (vv, i) {
                me.fetchService.channel(vv).then(res => {
                  if (res.code === 0) {
                    list[i] = res.data
                    temp.push(1)
                    if (temp.length === channelIds.length) {
                      resolve(temp)
                    }
                  }
                })
            })(v, index)
          })
        }).then(res => {
          this.guiyanNews = list
        })
      }
    }
  }
</script>


<style scoped lang="scss">
  @import "@/common/stylus/moon.scss";
  *::-webkit-media-controls-start-playback-button {
    display: none ;
    -webkit-appearance: none;
  }
  *::-webkit-media-controls-panel {
    display: none ;
    -webkit-appearance: none;
  }

  *::--webkit-media-controls-play-button {
    display: none ;
    -webkit-appearance: none;
  }
  .video {
    video {
      /*opacity: 0;*/
    }
    .poster {
      width:100%;
      height:100%;
      position: absolute;
      z-index:3;
      overflow:hidden;
      background-color: $theme-color;
      img {
        position: absolute;
        left:0;
        top:50%;
        transform:translateY(-50%);
        width:100%;
        height:auto;
      }
    }
    .self {
      position: relative;
      z-index:1;
      width:100%;height:100%;
      .left-bar {
        position: absolute;

      }
    }
  }
</style>

